package models

import (
	"encoding/csv"
	"io"
	"os"
	"path/filepath"

	"github.com/astaxie/beego"
)

type CallDetailRecord struct {
	CallerIdName      string
	CallerIdNumber    string
	DestinationNumber string
	Context           string
	StartStamp        string
	AnswerStamp       string
	EndStamp          string
	Duration          string
	BillSec           string
	HangupCause       string
	UuId              string
	LegUuId           string
	AccountCode       string
	ReadCodec         string
	WriteCodec        string
}

func GetAllCDR() []CallDetailRecord {
	var cdrs = make([]CallDetailRecord, 0)

	var cdr_file = filepath.Join(getFSLogDir(), "cdr-csv", "Master.csv")
	file, err := os.Open(cdr_file)
	if err != nil {
		return cdrs
	}
	defer file.Close()
	reader := csv.NewReader(file)
	for {
		record, err := reader.Read()
		if err == io.EOF {
			break
		} else if err != nil {
			return cdrs
		}
		cdr := getCDRFromRecord(record)
		cdrs = append(cdrs, *cdr)
	}

	return cdrs
}

func DelAllCDR() error {
	cdrDir := getCDRDir()

	filepath.Walk(cdrDir,
		func(path string, f os.FileInfo, err error) error {

			if !f.IsDir() {
				if err := os.Remove(path); err != nil {
					return err
				}
			}
			return nil
		})
	return nil
}

func getCDRFromRecord(record []string) *CallDetailRecord {
	if len(record) == 0 {
		return nil
	}

	var cdr CallDetailRecord
	cdr.CallerIdNumber = record[1]
	cdr.DestinationNumber = record[2]
	cdr.StartStamp = record[4]
	cdr.AnswerStamp = record[5]
	cdr.EndStamp = record[6]

	return &cdr
}

func getCDRDir() string {
	return filepath.Join(getFSLogDir(), "cdr-csv")
}

func getFSLogDir() string {
	return beego.AppConfig.String("fs_log_dir")
}
